import { Form, Button, Input, message } from 'antd';
import React, { useState, useCallback, useEffect } from 'react';
import { phoneNumFormat } from '@/utils/utils';

/**
 * @description: 表单手机验证码校验
 * @param {formLayout, form, onGetCode}
 * @return: React Node
 */
const PhoneValidate = function PhoneValidate(props) {
  const { form, formLayout, onGetCode: parentGetCode } = props;
  const { getFieldDecorator } = form;

  const [waiting, setWaiting] = useState(false);
  const [timer, setTimer] = useState(0);
  const [timeOutId, setTimeOutId] = useState(-1);
  const counter = useCallback(n => {
    if (n > 0) {
      setTimer(n - 1);
      setTimeOutId(setTimeout(() => counter(n - 1), 1000));
    } else {
      setWaiting(false);
    }
  }, []);

  useEffect(() => {
    return () => {
      clearTimeout(timeOutId);
    };
  }, [timeOutId]);

  const onGetCode = useCallback(() => {
    parentGetCode()
      .then(res => {
        message.info('验证码发送成功。');
        setWaiting(true);
        counter(180);
      })
      .catch(err => console.log);
  }, [counter, setWaiting, parentGetCode]);

  return (
    <>
      <Form.Item
        {...formLayout}
        label="系统预留手机号"
        extra={
          <Button disabled={waiting} onClick={onGetCode}>
            {waiting ? `${timer} 秒后重新获取` : '获取验证码'}
          </Button>
        }
      >
        {getFieldDecorator('phoneNum', {
          normalize: phoneNumFormat,
          rules: [
            {
              required: true,
              message: '请输入系统预留手机号',
            },
            {
              pattern: /^1[3-9][0-9]\s[0-9]{4}\s[0-9]{4}$/,
              message: '手机号格式不正确',
            },
          ],
        })(<Input size="large" maxLength={13} placeholder="请输入系统预留手机号" allowClear />)}
      </Form.Item>
      <Form.Item {...formLayout} label="验证码">
        {getFieldDecorator('smsCode', {
          rules: [{ required: true, message: '请输入验证码' }],
        })(<Input size="large" maxLength={6} placeholder="请输入验证码" allowClear />)}
      </Form.Item>
    </>
  );
};

export default PhoneValidate;
